{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "4\n",
      "None\n",
      "<function add at 0x00000124611E3378>\n",
      "1255759819640\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "#函数的定义以def开头，后面紧跟函数名，下面以一个简单的函数为例。\n",
    "def add(x,y):\n",
    "    z=x+y\n",
    "    print(z)\n",
    "    \n",
    "x=2\n",
    "add(x,x)\n",
    "#每个函数都有返回值，如果不写默认是None\n",
    "print(add(x,x))\n",
    "#函数也是对象\n",
    "print(add)\n",
    "print(id(add))\n",
    "print(isinstance(add,object))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "1\n",
      "[1, 2]\n",
      "[1, 2]\n"
     ]
    }
   ],
   "source": [
    "#实参形参的传递\n",
    "a=1\n",
    "def adda(a):\n",
    "  a+=1\n",
    "  return a\n",
    "\n",
    "print(add(a))\n",
    "print(a)\n",
    "b=[1]\n",
    "def addb(b):\n",
    "    b.append(2)\n",
    "    return b\n",
    "print(addb(b))\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-5-faa132fd6d10>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-5-faa132fd6d10>\"\u001b[1;36m, line \u001b[1;32m3\u001b[0m\n\u001b[1;33m    def addc(addb(b),c):\u001b[0m\n\u001b[1;37m                 ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "b=[1]\n",
    "c=2\n",
    "def addc(addb(b),c):\n",
    "    return addb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "17 1\n",
      "(17, 1)\n"
     ]
    }
   ],
   "source": [
    "#可以通过元组同时返回两个值，比如下面函数同时返回加和减的结果\n",
    "def add_sub(x,y):\n",
    "    return x+y,x-y\n",
    "a,b=add_sub(9,8)\n",
    "print(a,b)\n",
    "print(add_sub(9,8))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "ename": "UnboundLocalError",
     "evalue": "local variable 'z' referenced before assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mUnboundLocalError\u001b[0m                   Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-5-da9bd1ecab15>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     17\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     18\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mprint\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 19\u001b[1;33m \u001b[0madd2\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     20\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m<ipython-input-5-da9bd1ecab15>\u001b[0m in \u001b[0;36madd2\u001b[1;34m(x, y)\u001b[0m\n\u001b[0;32m      4\u001b[0m     \u001b[1;31m#函数内部对变量赋值，那么该变量的作用域就在函数内部\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m     \u001b[1;31m#比如z=x+y中的z就和函数外的z是没有关系的\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      7\u001b[0m     \u001b[0mz\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      8\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mUnboundLocalError\u001b[0m: local variable 'z' referenced before assignment"
     ]
    }
   ],
   "source": [
    "#变量的作用域\n",
    "z=3\n",
    "def add2(x,y):\n",
    "    #函数内部对变量赋值，那么该变量的作用域就在函数内部，相当于产生一个新的变量\n",
    "    #比如z=x+y中的z就和函数外的z是没有关系的\n",
    "    #如果在z=x+y之前加入print(z)则会出错\n",
    "    #local variable 'z' referenced before assignment\n",
    "    #本地变量z没有初始化就使用了\n",
    "    #print(z)\n",
    "    z=x+y\n",
    "    \n",
    "    print(locals())\n",
    "    print(globals()['z'])\n",
    "    #当我们输出变量的时候，首先找当前作用域有没有，\n",
    "    #然后在函数闭包中找（后面会讲）\n",
    "    #然后在全局的里面找\n",
    "    #最后在内置符号中找\n",
    "    print(x,y,z)\n",
    "    print(print)\n",
    "add2(3,2)\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "haha\n"
     ]
    }
   ],
   "source": [
    "#在if条件，for循环，while循环，with语句中不会产生新的作用域\n",
    "#在java里面遇到语句块{就会产生新的作用域，\n",
    "#比如下列语句中的x\n",
    "if True:\n",
    "    x='haha'\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "#函数参数\n",
    "#编写函数计算n次方，默认是平方，十进制\n",
    "#结果返回10进制整数\n",
    "#我们设置index的默认值为2，base的默认值为10\n",
    "def ncifang(value,index=2,base=10):\n",
    "    intvalue = int(value,base)\n",
    "    result = intvalue\n",
    "    for i in range(1,index):\n",
    "        result = result * intvalue\n",
    "    return result\n",
    "\n",
    "print(ncifang('10'))\n",
    "print(ncifang('10',base=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ahahaha\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "ncifang() got an unexpected keyword argument 'v'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                           Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-12-dff53a400a74>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      7\u001b[0m \u001b[1;31m#print(ncifang('10',value='10'))\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      8\u001b[0m \u001b[1;31m#指定了不认识的关键字\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mncifang\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mv\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'10'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: ncifang() got an unexpected keyword argument 'v'"
     ]
    }
   ],
   "source": [
    "#系统里面也有很多类似的函数\n",
    "print(\"ahahaha\",end=\"\\n\")\n",
    "#可能出错的情况\n",
    "#关键字参数后面跟默认参数\n",
    "#print(ncifang('10',index=2,2))\n",
    "#指定相同的参数\n",
    "#print(ncifang('10',value='10'))\n",
    "#指定了不认识的关键字\n",
    "#print(ncifang(v='10'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tuple'>\n",
      "6\n",
      "<class 'tuple'>\n",
      "3\n",
      "<class 'tuple'>\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "#不定长参数\n",
    "#求多个数字之和\n",
    "def sum(*values):\n",
    "    result=0\n",
    "    print(type(values))\n",
    "    for v in values:\n",
    "        result+=v\n",
    "    return result\n",
    "print(sum(1,2,3))\n",
    "r = range(3)\n",
    "#参数可以是个列表\n",
    "print(sum(*r))\n",
    "r2=[1,2,3,4]\n",
    "print(sum(*r2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#任务4.1 编写函数计算n次方和，默认是平方，十进制，如果输入，多个数字以不定参数方式输入\n",
    "# 如果参数是1，2，3 默认结果就是 1的平方+2的平方+3的平方=14\n",
    "#注意，关键字参数不能放不定长参数之前"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'dict'>\n",
      "100\n"
     ]
    }
   ],
   "source": [
    "#不定长关键字参数\n",
    "#某些情况下，对关键字参数也需要不定长,参数以**开头即可，本质上相当于是字典类型\n",
    "def ncifang2(**args):\n",
    "    print(type(args))\n",
    "    intvalue = int(args['value'],args['base'])\n",
    "    result = intvalue\n",
    "    for i in range(1,args['index']):\n",
    "        result = result * intvalue\n",
    "    return result\n",
    "\n",
    "args = {'value':'10','index':2,'base':10}\n",
    "print(ncifang2(**args))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "程序开始:2020-12-07 21:54:21.895531\n",
      "程序结束:2020-12-07 21:54:21.895531\n"
     ]
    }
   ],
   "source": [
    "#函数的默认值也可以是个动态类型，但在使用时务必小心\n",
    "#下面我们想定义一个log函数，记录程序执行的当前时间信息，可以用来测试一下函数的执行时间范围。\n",
    "from datetime import datetime\n",
    "from time import sleep\n",
    "def log(message,executetime=datetime.now()):\n",
    "    print(\"{}:{}\".format(message,executetime))\n",
    "    \n",
    "\n",
    "log('程序开始')\n",
    "sleep(3)\n",
    "log('程序结束')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "获取到当前时间:2020-12-07 21:54:42.328930\n"
     ]
    }
   ],
   "source": [
    "#通过上面结果可以看出，程序的开始时间和结束时间是一样的，我们明明sleep了3秒钟，为什么呢？\n",
    "#那是因为系统对于动态类型对象的默认值是在文件（模块）加载的时候初始化的，只初始化一次，后面每次调用只是使用这个初始化后的变量给参数赋值而已\n",
    "#我们稍微改变一下程序可以看出这个效果\n",
    "from datetime import datetime\n",
    "from time import sleep\n",
    "\n",
    "def getcurtime():\n",
    "    dt = datetime.now()\n",
    "    print('获取到当前时间:{}'.format(dt))\n",
    "    return dt\n",
    "\n",
    "def log(message,executetime=getcurtime()):\n",
    "    print(\"{}:{}\".format(message,executetime))\n",
    "    \n",
    "#即使不调用log函数，系统也会执行getcurtime,因为这是在文件（模块）加载的时候调用的\n",
    "#log('程序开始')\n",
    "#sleep(3)\n",
    "#log('程序结束')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "程序开始:2020-12-07 22:07:50.627657\n",
      "程序结束:2020-12-07 22:07:53.630157\n"
     ]
    }
   ],
   "source": [
    "#所以动态类型变量默认值应该用None，并且最好加上docstring来解释这个默认值\n",
    "from datetime import datetime\n",
    "from time import sleep\n",
    "def log(message,executetime=None):\n",
    "    \"\"\"函数作用是输出什么时间做了什么事情\n",
    "    \n",
    "    参数:\n",
    "        message:做了什么事情\n",
    "        executetime:什么时间运行的\n",
    "    \"\"\"\n",
    "    if not executetime:\n",
    "        executetime=datetime.now()\n",
    "    print(\"{}:{}\".format(message,executetime))\n",
    "    \n",
    "#可以发现结果差3秒左右，符合预期\n",
    "log('程序开始')\n",
    "sleep(3)\n",
    "log('程序结束')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
